package net.hn.hnms.biz.safety.water.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.api.feign.model.DataStateVo;
import net.hn.hnms.biz.api.mine.RemoteEquipmentService;
import net.hn.hnms.biz.api.safety.monitor.model.BaseSensorCoordDto;
import net.hn.hnms.biz.api.safety.water.model.StateTrendVo;
import net.hn.hnms.biz.api.safety.water.model.WaterAlarmVo;
import net.hn.hnms.biz.api.safety.water.model.WaterTodayInfoVo;
import net.hn.hnms.biz.safety.water.domain.*;
import net.hn.hnms.biz.safety.water.domain.vo.*;
import net.hn.hnms.biz.safety.water.mapper.*;
import net.hn.hnms.biz.safety.water.domain.dto.GushingdeBaseDto;
import net.hn.hnms.biz.safety.water.domain.dto.HoledeBaseHisDto;
import net.hn.hnms.biz.safety.water.domain.dto.HolerealDataDto;
import net.hn.hnms.biz.safety.water.domain.dto.HydrologyDataDto;
import net.hn.hnms.biz.safety.water.service.RiskMonitorWaterService;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName: RiskMonitorWaterServiceImpl
 * @Description 水害监测界面
 * @Author 王龙
 * @Date 2022-09-26
 * @Version 0.1
 */
@Service
public class RiskMonitorWaterServiceImpl implements RiskMonitorWaterService {
    /**
     * 长观孔基础
     */
    @Resource
    private HoledeBaseMapper holedeBaseMapper;
    /**
     * 长观孔实时
     */
    @Resource
    private HolerealNowMapper holerealNowMapper;
    /**
     * 长观孔报警
     */
    @Resource
    private HolealAbnormalMapper holealAbnormalMapper;
    /**
     * 排水报警
     */
    @Resource
    private DrainagealAbnormalMapper drainagealAbnormalMapper;
    /**
     * 排水量实时
     */
    @Resource
    private DrainagerealNowMapper drainagerealNowMapper;
    /**
     * 涌水量实时
     */
    @Resource
    private GushingrealNowPoMapper gushingrealNowPoMapper;

    /**
     * 涌水量基本信息
     */
    @Resource
    private GushingdeBaseMapper gushingdeBaseMapper;
    /**
     * 涌水量历史
     */
    @Resource
    private GushingrealHisMapper gushingrealHisMapper;

    /**
     * 排水量基本信息
     *
     * @return
     */
    @Resource
    private DrainagedeBaseMapper drainagedeBaseMapper;

    //远程调用重大设备
    @Resource
    private RemoteEquipmentService remoteEquipmentService;

    @Resource
    private WaterQualityMapper waterQualityMapper;

    /**
     * 今日信息
     *
     * @return
     */
    @Override
    public WaterTodayInfoVo todayInfo(String mineCode) {
        //返回数据Vo
        WaterTodayInfoVo waterTodayInfoVo = new WaterTodayInfoVo();
        //涌水量算法
        //今日累计涌水量 = 从今日00:00到现在的分钟数 x （当前所有测点的瞬时流量之和）
        //小保当是按小时算的，我看国家标准是立方米/分钟，砚北就用分钟吧
        //获取今日分钟数
        Date date = new Date();
        int minutes = (date.getHours() * 60) + date.getMinutes();
        //获取涌水量的数据
        //传感器类型
        String sensorType = "0503";
        List<GushingdeBaseDto> gushingdeBaseDtoList = gushingdeBaseMapper.selectBaseNowList(mineCode, sensorType);
        //累计涌水量
        BigDecimal inflowBigDecimal = new BigDecimal(0);
        //记录数不为空
        if (!gushingdeBaseDtoList.isEmpty()) {
            //循环累加涌水量
            for (GushingdeBaseDto gushingdeBaseDto : gushingdeBaseDtoList) {
                //判断数值是否为正数，
                if (gushingdeBaseDto.getPointValue().compareTo(BigDecimal.ZERO) == 1) {
                    inflowBigDecimal = inflowBigDecimal.add(gushingdeBaseDto.getPointValue());
                }
            }
            //所有累计量乘以时间分钟
            waterTodayInfoVo.setInflow(inflowBigDecimal.multiply(BigDecimal.valueOf(minutes)));
        } else {
            waterTodayInfoVo.setInflow(inflowBigDecimal);
        }

        //获取排水量的数据
//        List<DrainagedeBaseDto> drainagedeBaseDtoList = drainagedeBaseMapper.selectBaseNowList();
//        BigDecimal displacementBigDecimal = new BigDecimal(0);
//        //记录数不为空
//        if (!gushingdeBaseDtoList.isEmpty()) {
//            //循环累加涌水量
//            for (DrainagedeBaseDto drainagedeBaseDto : drainagedeBaseDtoList) {
//                //判断数值是否为正数，
//                if (drainagedeBaseDto.getPointValue().compareTo(BigDecimal.ZERO) == 1) {
//                    displacementBigDecimal = displacementBigDecimal.add(drainagedeBaseDto.getPointValue());
//                }
//            }
//            //所有累计量乘以时间分钟
//            waterTodayInfoVo.setDisplacement(displacementBigDecimal.multiply(BigDecimal.valueOf(minutes)));
//        } else {
//            waterTodayInfoVo.setDisplacement(displacementBigDecimal);
//        }
        BigDecimal todayAddDrainAwayWater = remoteEquipmentService.getTodayAddDrainAwayWater(mineCode);
        waterTodayInfoVo.setDisplacement(todayAddDrainAwayWater);
        return waterTodayInfoVo;
    }

    /**
     * 长观孔表格
     *
     * @return
     */
    @Override
    public List<HolealVo> macropore(String mineCode) {
        LambdaQueryWrapper<HolerealNowPo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), HolerealNowPo::getMineCode, mineCode);
        List<HolerealNowPo> holerealNowPos = holerealNowMapper.selectList(lambdaQueryWrapper);
        if (holerealNowPos.isEmpty()) {
            return new ArrayList<>();
        }
        List<HolealVo> collect = holerealNowPos.stream().map(t -> {
            //获取基础表的数据
            HoledeBasePo holedeBasePo = holedeBaseMapper.selectOne(new LambdaQueryWrapper<HoledeBasePo>()
                    .eq(HoledeBasePo::getPointCode, t.getPointCode())
                    .eq(StringUtils.isNotBlank(mineCode), HoledeBasePo::getMineCode, mineCode));
            HolealVo holealVo = new HolealVo();
            //测点名称
            holealVo.setPointName(t.getSensorLocation() != null ? t.getSensorLocation() : holedeBasePo.getSensorLocation());
            //水位
            holealVo.setWaterLevelValue(t.getWaterLevelValue());
            //水位单位
            holealVo.setWaterLevelUnit(t.getWaterLevelUnit());
            //水温值
            holealVo.setWaterTemperatureValue(t.getWaterTemperatureValue());
            //水温单位
            holealVo.setWaterTemperatureUnit(t.getWaterTemperatureUnit());
            //状态
            holealVo.setStatus(t.getPointStatus());
            //含水层
            if (holedeBasePo == null) {
                holealVo.setAquifer("");
                holealVo.setObservationDepth("");
            } else {
                holealVo.setAquifer(holedeBasePo.getObservationHorizon());
                holealVo.setObservationDepth(holedeBasePo.getObservationHorizon());
            }
            holealVo.setDataTime(t.getDataTime());
            // 埋深
            return holealVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 井下水文监测
     *
     * @return
     */
    @Override
    public List<HydrologyVo> hydrology(String mineCode) {
        List<HydrologyVo> list = new ArrayList<>();
        //井下水文监测查询排水量和涌水量的记录
        LambdaQueryWrapper<DrainagerealNowPo> drainagerealNowPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        drainagerealNowPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), DrainagerealNowPo::getMineCode, mineCode);
        List<DrainagerealNowPo> drainagerealNowPos = drainagerealNowMapper.selectList(drainagerealNowPoLambdaQueryWrapper);
        if (!drainagerealNowPos.isEmpty()) {
            for (DrainagerealNowPo drainagerealNowPo : drainagerealNowPos) {
                HydrologyVo hydrologyVo = new HydrologyVo();
                //位置
                hydrologyVo.setLocaltion(drainagerealNowPo.getPointLocation());
                //检测值
                hydrologyVo.setValue(drainagerealNowPo.getPointValue());
                //状态
                hydrologyVo.setStatus(drainagerealNowPo.getPointStatus());
                hydrologyVo.setDataTime(drainagerealNowPo.getDataTime());
                list.add(hydrologyVo);
            }
        }
        LambdaQueryWrapper<GushingrealNowPo> gushingrealNowPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        gushingrealNowPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), GushingrealNowPo::getMineCode, mineCode);
        List<GushingrealNowPo> gushingrealNowPos = gushingrealNowPoMapper.selectList(gushingrealNowPoLambdaQueryWrapper);
        if (!gushingrealNowPos.isEmpty()) {
            for (GushingrealNowPo gushingrealNowPo : gushingrealNowPos) {
                HydrologyVo hydrologyVo = new HydrologyVo();
                //位置
                hydrologyVo.setLocaltion(gushingrealNowPo.getSensorLocation());
                //检测值
                hydrologyVo.setValue(gushingrealNowPo.getPointValue());
                //状态
                hydrologyVo.setStatus(gushingrealNowPo.getPointStatus());
                hydrologyVo.setDataTime(gushingrealNowPo.getDataTime());
                list.add(hydrologyVo);
            }
        }
        return list;
    }

    /**
     * 今日报警
     *
     * @return
     */
    @Override
    public WaterAlarmVo alarm(String mineCode) {
        //监测指标（水温报警、水位报警、流量报警）

        //日期转换成字符串
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String str = format.format(date);
        String startTime = str + " 00:00:00";
        String endTime = str + " 23:59:59";
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = formatDate.parse(startTime);
            endDate = formatDate.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }


        WaterAlarmVo waterAlarmVo = new WaterAlarmVo();
        //流量
        LambdaQueryWrapper<HolealAbnormalPo> flowWrapper = new LambdaQueryWrapper<>();
        //流量报警条件
        flowWrapper.eq(HolealAbnormalPo::getExceptionType, "流量报警");
        //获取今天的数据
        flowWrapper.between(HolealAbnormalPo::getDataTime, startDate, endDate);
        flowWrapper.eq(StringUtils.isNotBlank(mineCode), HolealAbnormalPo::getMineCode, mineCode);
        Long flowCount = holealAbnormalMapper.selectCount(flowWrapper);
        waterAlarmVo.setFlow(flowCount.intValue());


        //水位
        LambdaQueryWrapper<HolealAbnormalPo> levelWrapper = new LambdaQueryWrapper<>();
        //水位报警条件
        levelWrapper.eq(HolealAbnormalPo::getExceptionType, "水位报警");
        //获取今天的数据
        levelWrapper.between(HolealAbnormalPo::getDataTime, startDate, endDate);
        levelWrapper.eq(StringUtils.isNotBlank(mineCode), HolealAbnormalPo::getMineCode, mineCode);
        Long levelCount = holealAbnormalMapper.selectCount(levelWrapper);
        waterAlarmVo.setLevel(levelCount.intValue());


        //水温
        LambdaQueryWrapper<HolealAbnormalPo> temperatureWrapper = new LambdaQueryWrapper<>();
        //水温报警条件
        temperatureWrapper.eq(HolealAbnormalPo::getExceptionType, "水温报警");
        //获取今天的数据
        temperatureWrapper.between(HolealAbnormalPo::getDataTime, startDate, endDate);
        temperatureWrapper.eq(StringUtils.isNotBlank(mineCode), HolealAbnormalPo::getMineCode, mineCode);
        Long temperatureCount = holealAbnormalMapper.selectCount(temperatureWrapper);
        waterAlarmVo.setTemperature(temperatureCount.intValue());
        return waterAlarmVo;
    }

    /**
     * 水害报警动态
     *
     * @return
     */
    @Override
    public StateTrendVo alarmTrend(String mineCode) {
        StateTrendVo stateTrendVo = new StateTrendVo();
        //x方向值
        List<String> dateList = new ArrayList<>();
        List<Integer> integerList = new ArrayList<>();
        Date dNow = new Date();   //当前时间
        Date dBefore = new Date();
        //七天的数据
        for (int i = 6; i >= 0; i--) {
            Calendar calendar = Calendar.getInstance(); //得到日历
            calendar.setTime(dNow);//把当前时间赋给日历
            calendar.add(Calendar.DATE, -i);  //设置为前一天，
            dBefore = calendar.getTime();   //设置为前一天时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
            String defaultStartDate = sdf.format(dBefore);    //格式化一天前
            try {
                Date time = sdf.parse(defaultStartDate);
                //时间
                dateList.add(defaultStartDate);
                //长观孔报警信息
                LambdaQueryWrapper<HolealAbnormalPo> holealAbnormalPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                holealAbnormalPoLambdaQueryWrapper.between(HolealAbnormalPo::getDataTime, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(defaultStartDate + " 00:00:00"), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(defaultStartDate + " 23:59:59"));
                holealAbnormalPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), HolealAbnormalPo::getMineCode, mineCode);
                Long holealAbnormalNumber = holealAbnormalMapper.selectCount(holealAbnormalPoLambdaQueryWrapper);

                //排水报警信息
                LambdaQueryWrapper<DrainagealAbnormalPo> drainagealAbnormalPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                drainagealAbnormalPoLambdaQueryWrapper.between(DrainagealAbnormalPo::getDataTime, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(defaultStartDate + " 00:00:00"), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(defaultStartDate + " 23:59:59"));
                drainagealAbnormalPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), DrainagealAbnormalPo::getMineCode, mineCode);
                Long drainagealAbnormalNumber = drainagealAbnormalMapper.selectCount(drainagealAbnormalPoLambdaQueryWrapper);
                //报警数量
                integerList.add(holealAbnormalNumber.intValue() + drainagealAbnormalNumber.intValue());
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

        }
        stateTrendVo.setCount(integerList);
        stateTrendVo.setXData(dateList);

        return stateTrendVo;
    }

    /**
     * 水害报警动态列表
     *
     * @return
     */
    @Override
    public List<AlarmTrendListVo> alarmTrendList() {
        //获取qi


        return null;
    }

    /**
     * 今日报警列表
     *
     * @param alarmType
     * @return
     */
    @Override
    public List<AlarmTrendListVo> alarmList(String alarmType, String mineCode) {


        //日期转换成字符串
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String str = format.format(date);
        String startTime = str + " 00:00:00";
        String endTime = str + " 23:59:59";
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = formatDate.parse(startTime);
            endDate = formatDate.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        LambdaQueryWrapper<HolealAbnormalPo> HolealAbnormalPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //报警条件(水温报警|水位报警|流量报警)
        HolealAbnormalPoLambdaQueryWrapper.eq(HolealAbnormalPo::getExceptionType, alarmType);
        //查询今天的报警
        HolealAbnormalPoLambdaQueryWrapper.between(HolealAbnormalPo::getDataTime, startDate, endDate);
        HolealAbnormalPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), HolealAbnormalPo::getMineCode, mineCode);
        List<HolealAbnormalPo> holealAbnormalPos = holealAbnormalMapper.selectList(HolealAbnormalPoLambdaQueryWrapper);
        if (holealAbnormalPos.isEmpty()) {
            return new ArrayList<>();
        }
        List<AlarmTrendListVo> collect = holealAbnormalPos.stream().map(t -> {
            AlarmTrendListVo alarmTrendListVo = new AlarmTrendListVo();
            //采集时间
            alarmTrendListVo.setAcquisitionTime(t.getDataTime());
            //水文类型
            alarmTrendListVo.setHydrologyType(t.getSensorType());
            //测点名称
            alarmTrendListVo.setPointName(t.getPorintCode());
            //测点位置
            alarmTrendListVo.setPointLocation(t.getSensorLocaltion());
            //监测类型
            alarmTrendListVo.setMonitorType(t.getExceptionType());
            //数据值
            //TODO 国家标准长观孔报警表没有监测值字段，根据业务暂时新增字段
            alarmTrendListVo.setValue(t.getSensorValue());
            //状态
            alarmTrendListVo.setStatus("");
            return alarmTrendListVo;
        }).collect(Collectors.toList());
        List<AlarmTrendListVo> alarmTrendListVoList = collect.stream().sorted(Comparator.comparing(AlarmTrendListVo::getAcquisitionTime).reversed()).collect(Collectors.toList());
        return alarmTrendListVoList;
    }

    /**
     * 数据查询-长观孔
     *
     * @param pageQuery
     * @param holerealDataDto
     * @return
     */
    @Override
    public ResponsePage<HolerealDataVo> dataQueryHolerealPageList(PageQuery pageQuery, HolerealDataDto holerealDataDto) {
        pageQuery.setPageNum(pageQuery.getPageNum() >= 1 ? pageQuery.getPageNum() * pageQuery.getPageSize() : 0);
        List<HoledeBaseHisDto> listHolereal = holedeBaseMapper.selectPageListHolereal(pageQuery, holerealDataDto);
        if (listHolereal.isEmpty()) {
            return new ResponsePage<>(new ArrayList(), 0);
        }
        //根据数据时间排序
        List<HoledeBaseHisDto> collect = listHolereal.stream().sorted(Comparator.comparing(HoledeBaseHisDto::getDataTime).reversed()).collect(Collectors.toList());
        List<HolerealDataVo> holerealDataVoList = collect.stream().map(t -> {
            HolerealDataVo holerealDataVo = new HolerealDataVo();
            //测点名称
            holerealDataVo.setPointName(t.getSensorLocation());
            //水位标高（M）
            holerealDataVo.setWaterLevelElevation(t.getWaterLevelValue());
            //水位标高单位
            holerealDataVo.setWaterLevelElevationUnit(t.getWaterLevelUnit());
            //水温（℃）
            holerealDataVo.setWaterTemperature(t.getWaterTemperatureValue());
            //水温单位
            holerealDataVo.setWaterTemperatureUnit(t.getWaterTemperatureUnit());
            //状态
            holerealDataVo.setStatus(t.getPointStatus());
            //目标含水层
            holerealDataVo.setTargetWaterLayer(t.getObservationHorizon());
            //监测时间
            holerealDataVo.setMonitoringTime(t.getDataTime());
            return holerealDataVo;
        }).collect(Collectors.toList());

        return new ResponsePage<>(holerealDataVoList, listHolereal.get(0).getTotal());
    }

    /**
     * 数据查询-井下水文
     *
     * @param pageQuery
     * @param holerealDataDto
     * @return
     */
    @Override
    public ResponsePage<HydrologyDataVo> dataQueryHydrologyPageList(PageQuery pageQuery, HydrologyDataDto holerealDataDto) {
        LambdaQueryWrapper<GushingrealHisPo> hisPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //数据时间
        hisPoLambdaQueryWrapper.gt(holerealDataDto.getStartTime() != null, GushingrealHisPo::getDataTime, holerealDataDto.getStartTime());
        hisPoLambdaQueryWrapper.lt(holerealDataDto.getEndTime() != null, GushingrealHisPo::getDataTime, holerealDataDto.getEndTime());
        //监测地点
        hisPoLambdaQueryWrapper.like(StringUtils.isNotBlank(holerealDataDto.getPointLocaltion()), GushingrealHisPo::getSensorLocation, holerealDataDto.getPointLocaltion());
        //测点名称
        hisPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(holerealDataDto.getPointName()), GushingrealHisPo::getPointCode, holerealDataDto.getPointName());
        //测点状态
        hisPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(holerealDataDto.getPointStatus()), GushingrealHisPo::getPointStatus, holerealDataDto.getPointStatus());
        hisPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(holerealDataDto.getMineCode()), GushingrealHisPo::getMineCode, holerealDataDto.getMineCode());
        //数据时间降序排列
        hisPoLambdaQueryWrapper.orderByDesc(GushingrealHisPo::getDataTime);
        Page<GushingrealHisPo> gushingrealHisPoPage = gushingrealHisMapper.selectPage(pageQuery.build(), hisPoLambdaQueryWrapper);
        //获取list
        List<GushingrealHisPo> records = gushingrealHisPoPage.getRecords();
        if (records.isEmpty()) {
            return new ResponsePage<>(new ArrayList(), 0);
        }
        List<HydrologyDataVo> collect = records.stream().map(t -> {
            HydrologyDataVo hydrologyDataVo = new HydrologyDataVo();
            //监测地点
            hydrologyDataVo.setPointLocaltion(t.getSensorLocation());

            //测点名称
            hydrologyDataVo.setPointName(t.getPointCode());

            //检测值
            hydrologyDataVo.setPointValue(t.getPointValue());
            //监测单位
            hydrologyDataVo.setPointUnit(t.getPointUnit());

            //状态
            hydrologyDataVo.setPointStatus(t.getPointStatus());

            //监测时间
            hydrologyDataVo.setMonitoringTime(t.getDataTime());

            return hydrologyDataVo;
        }).collect(Collectors.toList());

        //排序降序
        List<HydrologyDataVo> list = collect.stream().sorted(Comparator.comparing(HydrologyDataVo::getMonitoringTime).reversed()).collect(Collectors.toList());

        return new ResponsePage<>(list, gushingrealHisPoPage.getTotal());
    }

    /**
     * 数据查询-长观孔下拉框-测点名称
     *
     * @return
     */
    @Override
    public List<String> dataQueryHolerealPointName(String mineCode) {
        //获取长观孔Base的所有测点名称
        LambdaQueryWrapper<HoledeBasePo> holedeBasePoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        holedeBasePoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), HoledeBasePo::getMineCode, mineCode);
        List<HoledeBasePo> holedeBasePos = holedeBaseMapper.selectList(holedeBasePoLambdaQueryWrapper);
        if (holedeBasePos.isEmpty()) {
            return new ArrayList<>();
        }
        List<String> collect = holedeBasePos.stream().map(t -> {
//            String str = new String();
//            str = t.getSensorLocation();
            return new String(t.getSensorLocation());
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 数据查询-井下水文下拉框-测点名称
     *
     * @return
     */
    @Override
    public List<String> dataQueryHydrologyPointName(String mineCode) {

        List<GushingdeBasePo> gushingdeBasePos = gushingdeBaseMapper.selectList(new LambdaQueryWrapper<GushingdeBasePo>().eq(StringUtils.isNotBlank(mineCode), GushingdeBasePo::getMineCode, mineCode));
        if (gushingdeBasePos.isEmpty()) {
            return new ArrayList<>();
        }
        List<String> collect = gushingdeBasePos.stream().map(t -> {
            return new String(t.getPointCode());
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 数据查询-井下水文下拉框-监测地点
     *
     * @return
     */
    @Override
    public List<String> dataQueryHydrologyPointLocaltion(String mineCode) {
        List<GushingdeBasePo> gushingdeBasePos = gushingdeBaseMapper.selectList(new LambdaQueryWrapper<GushingdeBasePo>().eq(StringUtils.isNotBlank(mineCode), GushingdeBasePo::getMineCode, mineCode));
        if (gushingdeBasePos.isEmpty()) {
            return new ArrayList<>();
        }
        List<String> collect = gushingdeBasePos.stream().map(t -> {
            return new String(t.getPointLocation());
        }).collect(Collectors.toList());
        return collect;

    }

    /**
     * 数据查询(实时)-长观孔条件分页列表
     *
     * @param pageQuery
     * @param holerealDataDto
     * @return
     */
    @Override
    public ResponsePage<HolerealDataVo> dataQueryNowHolerealPageList(PageQuery pageQuery, HolerealDataDto holerealDataDto) {
        pageQuery.setPageNum(pageQuery.getPageNum() >= 1 ? pageQuery.getPageNum() * pageQuery.getPageSize() : 0);
        //base和实时表关联查询
        List<HoledeBaseHisDto> listHolereal = holedeBaseMapper.selectPageListHolerealNow(pageQuery, holerealDataDto);
        if (listHolereal.isEmpty()) {
            return new ResponsePage<>(new ArrayList(), 0);
        }
        //根据数据时间排序
        List<HoledeBaseHisDto> collect = listHolereal.stream().sorted(Comparator.comparing(HoledeBaseHisDto::getDataTime).reversed()).collect(Collectors.toList());
        List<HolerealDataVo> holerealDataVoList = collect.stream().map(t -> {
            HolerealDataVo holerealDataVo = new HolerealDataVo();
            //测点名称
            holerealDataVo.setPointName(t.getSensorLocation());
            //水位标高（M）
            holerealDataVo.setWaterLevelElevation(t.getWaterLevelValue());
            //水位标高单位
            holerealDataVo.setWaterLevelElevationUnit(t.getWaterLevelUnit());
            //水温（℃）
            holerealDataVo.setWaterTemperature(t.getWaterTemperatureValue());
            //水温单位
            holerealDataVo.setWaterTemperatureUnit(t.getWaterTemperatureUnit());
            //状态
            holerealDataVo.setStatus(t.getPointStatus());
            //目标含水层
            holerealDataVo.setTargetWaterLayer(t.getObservationHorizon());
            //监测时间
            holerealDataVo.setMonitoringTime(t.getDataTime());
            return holerealDataVo;
        }).collect(Collectors.toList());

        return new ResponsePage<>(holerealDataVoList, listHolereal.get(0).getTotal());
    }

    /**
     * 数据查询（实时）-井下水文条件分页列表
     *
     * @param pageQuery
     * @param holerealDataDto
     * @return
     */
    @Override
    public ResponsePage<HydrologyDataVo> dataQueryNowHydrologyPageList(PageQuery pageQuery, HydrologyDataDto holerealDataDto) {
        LambdaQueryWrapper<GushingrealNowPo> hisPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //数据时间
        hisPoLambdaQueryWrapper.gt(holerealDataDto.getStartTime() != null, GushingrealNowPo::getDataTime, holerealDataDto.getStartTime());
        hisPoLambdaQueryWrapper.lt(holerealDataDto.getEndTime() != null, GushingrealNowPo::getDataTime, holerealDataDto.getEndTime());
        //监测地点
        hisPoLambdaQueryWrapper.like(StringUtils.isNotBlank(holerealDataDto.getPointLocaltion()), GushingrealNowPo::getSensorLocation, holerealDataDto.getPointLocaltion());
        //测点名称
        hisPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(holerealDataDto.getPointName()), GushingrealNowPo::getPointCode, holerealDataDto.getPointName());
        //测点状态
        hisPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(holerealDataDto.getPointStatus()), GushingrealNowPo::getPointStatus, holerealDataDto.getPointStatus());
        hisPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(holerealDataDto.getMineCode()), GushingrealNowPo::getMineCode, holerealDataDto.getMineCode());
        //数据时间降序排列
        hisPoLambdaQueryWrapper.orderByDesc(GushingrealNowPo::getDataTime);
        Page<GushingrealNowPo> gushingrealHisPoPage = gushingrealNowPoMapper.selectPage(pageQuery.build(), hisPoLambdaQueryWrapper);
        //获取list
        List<GushingrealNowPo> records = gushingrealHisPoPage.getRecords();
        if (records.isEmpty()) {
            return new ResponsePage<>(new ArrayList(), 0);
        }
        List<HydrologyDataVo> collect = records.stream().map(t -> {
            HydrologyDataVo hydrologyDataVo = new HydrologyDataVo();
            //监测地点
            hydrologyDataVo.setPointLocaltion(t.getSensorLocation());

            //测点名称
            hydrologyDataVo.setPointName(t.getPointCode());

            //检测值
            hydrologyDataVo.setPointValue(t.getPointValue());
            //监测单位
            hydrologyDataVo.setPointUnit(t.getPointUnit());

            //状态
            hydrologyDataVo.setPointStatus(t.getPointStatus());

            //监测时间
            hydrologyDataVo.setMonitoringTime(t.getDataTime());

            return hydrologyDataVo;
        }).collect(Collectors.toList());

        //排序降序
        List<HydrologyDataVo> list = collect.stream().sorted(Comparator.comparing(HydrologyDataVo::getMonitoringTime).reversed()).collect(Collectors.toList());

        return new ResponsePage<>(list, gushingrealHisPoPage.getTotal());
    }

    @Override
    public List<DataStateVo> getHolerealMaxTime(String mineCode, String companyCode) {
        QueryWrapper<HolerealNowPo> wrapper = new QueryWrapper<>();
        wrapper.select("mine_code as minecode, max(create_time) as maxtime")
                .groupBy("mine_code");
        List<Map<String, Object>> maps = holerealNowMapper.selectMaps(wrapper);
        List<DataStateVo> list = new ArrayList<>();
        maps.forEach(s -> {
            DataStateVo vo = new DataStateVo();
            vo.setMaxTime((Date) s.get("maxtime"));
            vo.setMineCode((String) s.get("minecode"));
            list.add(vo);
        });
        return list;
    }

    @Override
    public List<DataStateVo> getPSLMaxTime(String mineCode, String companyCode) {
        QueryWrapper<DrainagerealNowPo> wrapper = new QueryWrapper<>();
        wrapper.select("mine_code as minecode, max(data_time) as maxtime")
                .groupBy("mine_code");
        List<Map<String, Object>> maps = drainagerealNowMapper.selectMaps(wrapper);
        List<DataStateVo> list = new ArrayList<>();
        maps.forEach(s -> {
            DataStateVo vo = new DataStateVo();
            vo.setMaxTime((Date) s.get("maxtime"));
            vo.setMineCode((String) s.get("minecode"));
            list.add(vo);
        });
        return list;
    }

    @Override
    public List<DataStateVo> getYSLMaxTime(String mineCode, String companyCode) {
        QueryWrapper<GushingrealNowPo> wrapper = new QueryWrapper<>();
        wrapper.select("mine_code as minecode, max(create_time) as maxtime")
                .groupBy("mine_code");
        List<Map<String, Object>> maps = gushingrealNowPoMapper.selectMaps(wrapper);
        List<DataStateVo> list = new ArrayList<>();
        maps.forEach(s -> {
            DataStateVo vo = new DataStateVo();
            vo.setMaxTime((Date) s.get("maxtime"));
            vo.setMineCode((String) s.get("minecode"));
            list.add(vo);
        });
        return list;
    }

    /**
     * 获取水害防治BaseSensorTable表所有信息
     *
     * @return
     */
    @Override
    public List<BaseSensorCoordDto> getBaseSensorTableAllList(String mineCode) {
        //获取长观孔的基础数据
        List<BaseSensorCoordDto> baseSensorCoordDtos = new ArrayList<>();
        LambdaQueryWrapper<HoledeBasePo> holedeBasePoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        holedeBasePoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), HoledeBasePo::getMineCode, mineCode);
        List<HoledeBasePo> holedeBasePos = holedeBaseMapper.selectList(holedeBasePoLambdaQueryWrapper);
        if (!holedeBasePos.isEmpty()) {
            holedeBasePos.stream().forEach(holedeBasePo -> {
                BaseSensorCoordDto baseSensorCoordDto = new BaseSensorCoordDto();
                //传感器编码 分站编码
                baseSensorCoordDto.setPointCode(holedeBasePo.getPointCode());
                //传感器名称 分站名称
                baseSensorCoordDto.setLocation(holedeBasePo.getSensorLocation());
                //传感器类型编码
                baseSensorCoordDto.setSensorTypeCode("CGK");
                //传感器类型名称
                baseSensorCoordDto.setSensorTypeName("长观孔");
                //x
                baseSensorCoordDto.setXCoordinate(new BigDecimal(holedeBasePo.getXCoordinate()));
                //y
                baseSensorCoordDto.setYCoordinate(new BigDecimal(holedeBasePo.getYCoordinate()));
                //z
                baseSensorCoordDto.setZCoordinate(new BigDecimal(holedeBasePo.getZCoordinate()));
                baseSensorCoordDtos.add(baseSensorCoordDto);
            });
        }

        //获取排水量base数据
        LambdaQueryWrapper<DrainagedeBasePo> drainagedeBasePoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        drainagedeBasePoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), DrainagedeBasePo::getMineCode, mineCode);
        List<DrainagedeBasePo> drainagedeBasePos = drainagedeBaseMapper.selectList(drainagedeBasePoLambdaQueryWrapper);
        if (!drainagedeBasePos.isEmpty()) {
            drainagedeBasePos.stream().forEach(drainagedeBasePo -> {
                BaseSensorCoordDto baseSensorCoordDto = new BaseSensorCoordDto();
                //传感器编码 分站编码
                baseSensorCoordDto.setPointCode(drainagedeBasePo.getPointCode());
                //传感器名称 分站名称
                baseSensorCoordDto.setLocation(drainagedeBasePo.getPointLocation());
                //传感器类型编码
                baseSensorCoordDto.setSensorTypeCode("PSL");
                //传感器类型名称
                baseSensorCoordDto.setSensorTypeName("排水量");
                //x
                baseSensorCoordDto.setXCoordinate(new BigDecimal(drainagedeBasePo.getXCoordinate()));
                //y
                baseSensorCoordDto.setYCoordinate(new BigDecimal(drainagedeBasePo.getYCoordinate()));
                //z
                baseSensorCoordDto.setZCoordinate(new BigDecimal(drainagedeBasePo.getZCoordinate()));
                baseSensorCoordDtos.add(baseSensorCoordDto);
            });
        }

        //获取用水量base数据
        LambdaQueryWrapper<GushingdeBasePo> gushingdeBasePoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        gushingdeBasePoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), GushingdeBasePo::getMineCode, mineCode);
        List<GushingdeBasePo> gushingdeBasePos = gushingdeBaseMapper.selectList(gushingdeBasePoLambdaQueryWrapper);
        if (!gushingdeBasePos.isEmpty()) {
            gushingdeBasePos.stream().forEach(gushingdeBasePo -> {
                BaseSensorCoordDto baseSensorCoordDto = new BaseSensorCoordDto();
                //传感器编码 分站编码
                baseSensorCoordDto.setPointCode(gushingdeBasePo.getPointCode());
                //传感器名称 分站名称
                baseSensorCoordDto.setLocation(gushingdeBasePo.getPointLocation());
                //传感器类型编码
                baseSensorCoordDto.setSensorTypeCode("YSL");
                //传感器类型名称
                baseSensorCoordDto.setSensorTypeName("涌水量");
                //x
                baseSensorCoordDto.setXCoordinate(new BigDecimal(gushingdeBasePo.getXCoordinate()));
                //y
                baseSensorCoordDto.setYCoordinate(new BigDecimal(gushingdeBasePo.getYCoordinate()));
                //z
                baseSensorCoordDto.setZCoordinate(new BigDecimal(gushingdeBasePo.getZCoordinate()));
                baseSensorCoordDtos.add(baseSensorCoordDto);
            });

        }
        return baseSensorCoordDtos;
    }

    @Override
    public WaterQuality waterQuality(String mineCode) {
        LambdaQueryWrapper<WaterQuality> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(WaterQuality::getDataTime).last("LIMIT 1");
        return waterQualityMapper.selectOne(lambdaQueryWrapper);
    }

    /**
     * 测点统计
     *
     * @return
     */
    @Override
    public PointStatisticsVo indicator(String mineCode) {
        PointStatisticsVo pointStatisticsVo = new PointStatisticsVo();
        //长观孔数量
        LambdaQueryWrapper<HolerealNowPo> holerealNowPoLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        holerealNowPoLambdaQueryWrapper1.eq(StringUtils.isNotBlank(mineCode), HolerealNowPo::getMineCode, mineCode);
        List<HolerealNowPo> holerealNowPos = holerealNowMapper.selectList(holerealNowPoLambdaQueryWrapper1);
        pointStatisticsVo.setHolealNumber(holerealNowPos.size());
        //长观孔在线数量
        //在线数据算法（测点状态:0,dataTime和creartTime时间不能相差五分钟）
        LambdaQueryWrapper<HolerealNowPo> holerealNowPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //0  标识测点正常
        holerealNowPoLambdaQueryWrapper.eq(HolerealNowPo::getPointStatus, "0");
        holerealNowPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), HolerealNowPo::getMineCode, mineCode);
        List<HolerealNowPo> holerealNowPoList = holerealNowMapper.selectList(holerealNowPoLambdaQueryWrapper);
        //有记录数
        if (!holerealNowPoList.isEmpty()) {
//            int count = 0;
//            //遍历数据
//            for (HolerealNowPo holerealNowPo : holerealNowPoList) {
//                //数据时间和创建时间不可以为空
//                if (holerealNowPo.getDataTime() != null && holerealNowPo.getCreateTime() != null) {
//                    try {
//                        //获取时间差
//                        long time = this.getTime(holerealNowPo.getCreateTime(), holerealNowPo.getDataTime());
//                        //时间差五分钟之内
//                        if (time >= 0 && time <= 5) {
//                            count++;
//                        }
//
//                    } catch (ParseException e) {
//                        throw new RuntimeException(e);
//                    }
//                }
//            }
//            pointStatisticsVo.setHolealOnLineNumber(count);
            pointStatisticsVo.setHolealOnLineNumber(holerealNowPoList.size());
//            count = 0;
        } else {

            pointStatisticsVo.setHolealOnLineNumber(0);
        }

        //长观孔报警
        //获取实时表时间
        if (!holerealNowPos.isEmpty()) {
            HolerealNowPo holerealNowPo = holerealNowPos.get(0);
            LambdaQueryWrapper<HolealAbnormalPo> holealAbnormalPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            holealAbnormalPoLambdaQueryWrapper.eq(HolealAbnormalPo::getDataTime, holerealNowPo.getDataTime());
            holealAbnormalPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), HolealAbnormalPo::getMineCode, mineCode);
            Long holealAbnormalNumber = holealAbnormalMapper.selectCount(holealAbnormalPoLambdaQueryWrapper);
            pointStatisticsVo.setHolealAlarmNumber(holealAbnormalNumber.intValue());
        } else {
            pointStatisticsVo.setHolealAlarmNumber(0);
        }

        //井下水文测点数（涌水和排水）

        Long drainagerealNumber = drainagerealNowMapper.selectCount(new LambdaQueryWrapper<DrainagerealNowPo>().eq(StringUtils.isNotBlank(mineCode), DrainagerealNowPo::getMineCode, mineCode));
        Long gushingrealNumber = gushingrealNowPoMapper.selectCount(new LambdaQueryWrapper<GushingrealNowPo>().eq(StringUtils.isNotBlank(mineCode), GushingrealNowPo::getMineCode, mineCode));
        pointStatisticsVo.setHydrologyNumber(drainagerealNumber.intValue() + gushingrealNumber.intValue());
        //井下水文在线数量
        LambdaQueryWrapper<DrainagerealNowPo> drainagerealNowPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //00000000  标识侧点正常
        //drainagerealNowPoLambdaQueryWrapper.eq(DrainagerealNowPo::getPointStatus, "00000000");
        drainagerealNowPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), DrainagerealNowPo::getMineCode, mineCode);
        Long drainagerealNowNumber = drainagerealNowMapper.selectCount(drainagerealNowPoLambdaQueryWrapper);
        LambdaQueryWrapper<GushingrealNowPo> gushingrealNowPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //00000000  标识侧点正常
        //gushingrealNowPoLambdaQueryWrapper.eq(GushingrealNowPo::getPointStatus, "00000000");
        gushingrealNowPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), GushingrealNowPo::getMineCode, mineCode);
        Long gushingrealNowNumber = gushingrealNowPoMapper.selectCount(gushingrealNowPoLambdaQueryWrapper);
        pointStatisticsVo.setHydrologyOnLineNumber(drainagerealNowNumber.intValue() + gushingrealNowNumber.intValue());
        //井下水文报警数
        List<DrainagerealNowPo> drainagerealNowPos = drainagerealNowMapper.selectList(new LambdaQueryWrapper<DrainagerealNowPo>().eq(StringUtils.isNotBlank(mineCode), DrainagerealNowPo::getMineCode, mineCode));

        //涌水没有报警
        //List<GushingrealNowPo> gushingrealNowPos = gushingrealNowPoMapper.selectList(null);
        if (!drainagerealNowPos.isEmpty()) {
            Date dataTime = drainagerealNowPos.get(0).getDataTime();
            //根据实时表的时间查询报警表数据
            LambdaQueryWrapper<DrainagealAbnormalPo> drainagealAbnormalPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            drainagealAbnormalPoLambdaQueryWrapper.eq(DrainagealAbnormalPo::getDataTime, dataTime);
            drainagealAbnormalPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), DrainagealAbnormalPo::getMineCode, mineCode);
            Long drainagealAbnormalNumber = drainagealAbnormalMapper.selectCount(drainagealAbnormalPoLambdaQueryWrapper);
            pointStatisticsVo.setHydrologyAlarmNumber(drainagealAbnormalNumber.intValue());
        } else {
            pointStatisticsVo.setHydrologyAlarmNumber(0);

        }
        return pointStatisticsVo;
    }

    // 获取两个时间相差分钟数
    public long getTime(String newTime, String oldTime) throws ParseException {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long NTime = df.parse(newTime).getTime();
        //从对象中拿到时间
        long OTime = df.parse(oldTime).getTime();
        long diff = (NTime - OTime) / 1000 / 60;
        return diff;
    }

    // 获取两个时间相差分钟数
    public long getTime(Date newTime, Date oldTime) throws ParseException {
        long NTime = newTime.getTime();
        //从对象中拿到时间
        long OTime = oldTime.getTime();
        long diff = (NTime - OTime) / 1000 / 60;
        return diff;
    }


}
